from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api import include_router_handle, register_exceptions, reset_api_docs
from app.core import logger_manager, settings
from app.database.db import (
    auto_commit_session,
    check_db_connection,
    close_engine,
    init_async_engine,
)
from app.database.redis import close_async_redis_pool, get_redis, init_async_redis_pool
from app.service.role_service import RoleService

# from app.websocket.connection_manager import manager

# from app.service.websocket_service import get_websocket_service

# from app.utils.mdc_middleware import setup_mdc_middleware

logger = logger_manager.get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 初始化
    init_async_engine()
    await init_async_redis_pool()

    # 可选：启动时检查连接
    assert await check_db_connection(), "数据库不可用"
    # assert await check_redis_connection(), "Redis不可用"

    redis = await get_redis()
    async with auto_commit_session() as session:
        # 创建RoleMenuService实例
        role_service = RoleService(session=session, redis=redis, settings=settings)

        # 初始化权限缓存
        await role_service.refresh_role_perms_cache()

        logger.info("角色权限缓存初始化成功")

    # 初始化WebSocket服务
    # websocket_service = await get_websocket_service()
    # logger.info("WebSocket服务初始化成功")
    # 启动 Redis Pub/Sub 监听器
    # pubsub = redis.pubsub()
    # await pubsub.subscribe("stomp:topic:dict", "stomp:topic:notice", "stomp:topic:online-count")

    # async def redis_listener():
    #     async for message in pubsub.listen():
    #         if message["type"] == "message":
    #             await manager.handle_redis_message(message["channel"], message["data"])

    # task = asyncio.create_task(redis_listener())

    yield

    # 关闭WebSocket服务
    # await websocket_service.close()
    # logger.info("WebSocket服务已关闭")

    # 关闭
    await close_async_redis_pool()
    await close_engine()

    # task.cancel()


# 创建FastAPI应用实例
app = FastAPI(
    title=settings.PROJECT_NAME,
    description=settings.PROJECT_NAME,
    version=settings.VERSION,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,
)
reset_api_docs()
include_router_handle(app)

# 注册全局异常处理器
register_exceptions(app)

# 注册中间件
# app.add_middleware(APILoggingMiddleware)
# setup_mdc_middleware(app)  # 新增：设置 MDC 中间件

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    """根端点，返回应用信息"""
    return {"message": "GoldenChannelERP API", "version": "1.0.0"}


@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host=settings.HOST, port=settings.PORT, reload=True)
    uvicorn.run(app, host=settings.HOST, port=settings.PORT, reload=True)
